#!/bin/bash

set -x

# default to update source then build

TOP_DIR=$(pwd)
SRC_DIR=$TOP_DIR/lib_source
BD_DIR=$TOP_DIR/lib_build
BIN_DIR=$TOP_DIR/lib_bin

VER_SDL=2.0.0

export PATH=$TOP_DIR/cross/bin:$PATH

# export MAKE_OPT="-j 2"

cmd=all64
if [ -n "$1" ] ; then
	cmd=$1
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "update" ] ; then
	mkdir -p $SRC_DIR || exit 0
	cd $SRC_DIR
	if [ ! -d SDL2-$VER_SDL ] ; then
		wget http://www.libsdl.org/release/SDL2-$VER_SDL.tar.gz
		tar xzf SDL2-$VER_SDL.tar.gz
	fi
	cd ..
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "b64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
	HOST_FLAG="--host=x86_64-w64-mingw32"
	if [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
		HOST_FLAG="--host=i686-w64-mingw32"
	fi
	rm -rf $BIN_DIR/SDL
	mkdir -p $BD_DIR
	cd $BD_DIR
	rm -rf bd_SDL
	mkdir bd_SDL
	cd bd_SDL
	$SRC_DIR/SDL2-$VER_SDL/configure $HOST_FLAG --prefix=$BIN_DIR/SDL \
			--disable-haptic \
			--enable-shared --disable-static

# TODO : unable to build shared library, libtool complain undefined symbol
#			--enable-shared --disable-static

	make $MAKE_OPT
#	if [ -f build/.libs/SDL_windows_main.o ] && [ ! -e build/SDL_windows_main.o ] ; then
#		cp build/.libs/SDL_windows_main.o build/SDL_windows_main.o
#	fi
	cp build/.libs/SDL_windows_main.o build/SDL_windows_main.o
	make $MAKE_OPT
	cp build/.libs/SDL_test_*.o build/
	make $MAKE_OPT
	make install
#	patch -d $SRC_DIR/SDL -p0 -R < $TOP_DIR/patch/sdl.patch
	cd ..
	cd ..
fi

